package cn.ynrcb.personnelfile.sysadmin.service.impl;


import cn.ynrcb.personnelfile.common.exception.MyException;
import cn.ynrcb.personnelfile.common.utils.DateUtils;
import cn.ynrcb.personnelfile.sysadmin.dao.SysCaptchaDao;
import cn.ynrcb.personnelfile.sysadmin.entity.SysCaptchaEntity;
import cn.ynrcb.personnelfile.sysadmin.service.SysCaptchaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.code.kaptcha.Producer;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.util.Date;

/**
 * 图片验证码
 * @author swb
 * @version created at 2020年4月20日 下午3:57:26
 */
@Service("sysCaptchaService")
public class SysCaptchaServiceImpl extends ServiceImpl<SysCaptchaDao, SysCaptchaEntity> implements SysCaptchaService {

    private final Producer producer;

    public SysCaptchaServiceImpl(Producer producer) {
        this.producer = producer;
    }

    @Override
    public BufferedImage getCaptcha(String uuid) {
        if(StringUtils.isBlank(uuid)){
            throw new MyException("uuid不能为空");
        }
        //生成文字验证码
        String code = producer.createText();

        SysCaptchaEntity captchaEntity = new SysCaptchaEntity();
        captchaEntity.setUuid(uuid);
        captchaEntity.setCode(code);
        //10分钟后过期
        captchaEntity.setExpireTime(DateUtils.addDateMinutes(new Date(), 10));
        this.save(captchaEntity);

        return producer.createImage(code);
    }



    @Override
    public boolean validate(String uuid, String code) {
    	SysCaptchaEntity captchaEntity = this.getById(uuid);
        if(captchaEntity == null){
            return false;
        }
        String captchaCode = captchaEntity.getCode();

        if(captchaCode.equalsIgnoreCase(code)){
        	baseMapper.deleteById(uuid);
            return true;
        }

        return false;
    }



	@Override
	public void saveCaptcha(SysCaptchaEntity captcha) {
		captcha.setExpireTime(DateUtils.addDateMinutes(new Date(), 10));
		this.save(captcha);
	}



	@Override
	public String getCode(String id) {
		String code = "";
		SysCaptchaEntity captcha = baseMapper.getCodeByID(id);
		if(null != captcha) {
			code = captcha.getCode();
			baseMapper.deleteById(id);
		}
		return code;
	}



	@Override
	public void updateCaptcha(SysCaptchaEntity captcha) {
		captcha.setExpireTime(DateUtils.addDateMinutes(new Date(), 10));
		this.updateById(captcha);
	}
}
